# coding:utf-8
# writingtime: 2022-8-11

import os
import time
import pandas as pd
import numpy as np
import random as rm
from math import log10


class GetTestData:
    def __init__(self, deviationsize=None):
        """
        function：生成得分函数的测试数据
        :param deviationsize: 偏移量
        """
        if deviationsize is None:
            self.deviation = 0.1
        else:
            self.deviation = deviationsize

    def auxiliaryfunction(self, length):
        """
        function: 辅助函数，根据线段长度生成所有可能
        :param length: 线段长度
        :return:
        """
        numb_round = int(log10(1 / self.deviation))
        list_temp = []
        temp = np.array([0, length])
        while temp[1] < 1:
            list_temp.append([round(temp[0], numb_round), round(temp[1], numb_round)])
            temp += self.deviation
        return list_temp

    def getlinerandom(self, L1):
        """
        生成一个区间，区间的长度为：L1
        随机构造一个线段 |_________|
        :param L1:
        :return:
        """
        numb_round = int(log10(1 / self.deviation))
        add = round(rm.random(), numb_round)
        sub = round(add - L1, numb_round)
        while sub < 0:
            add = round(rm.random(), numb_round)
            sub = round(add - L1, numb_round)
        line = [sub, add]
        return line

    def getrondomivq_rof(self, L1, L2):
        """
        任意区间值广义正交模糊数,生成了两个区间，[x1,x2,y1,y2] 每个区间的长度都为l1，l2
        :param L1:U部分长度
        :param L2:V部分长度
        :return:
        """
        u = self.getlinerandom(L1)
        v = self.getlinerandom(L2)
        ivqrof = [u, v]

        return ivqrof

    def makedir(self, dirnames):
        """
        function: 创建文件夹
        :param dirnames: 文件夹名
        :return:
        """
        try:
            os.makedirs(dirnames)
        except:
            print("folder already exists")

    def case1(self):
        """
        function:L1=L2=L3=L4=0,x1≠x2,y1≠y2,写入得分的计算
        :return:
        """

        star = time.time()

        path = r'data\case1'
        path2 = r'result\case1'
        co = 1
        filename = os.path.join(path, str(co) + '.csv')
        resultname = os.path.join(path2, str(co) + '.csv')
        self.makedir(path)
        self.makedir(path2)
        temp = np.arange(0, 1, 0.01)
        # 精度
        numb_round = int(log10(1 / self.deviation))
        count = 1
        flag = True
        from scoreFunction import getScore_new
        for i in temp:
            e = time.time()
            for j in temp:
                if flag:
                    ee = time.time()
                    data = pd.DataFrame({'ul': [i for _ in range(10000)],
                                         'ur': [j for _ in range(10000)],
                                         'vl': [k for k in list(temp) for _ in range(100)],
                                         'vr': [k for _ in range(100) for k in list(temp)]})
                    # 写入case1的案例数据
                    # data.to_csv(filename, index=False, header=False)
                    # temp_set.update(list(data.apply(lambda x:self.func(x[0],x[1],x[2],x[3]),axis=1)))
                    ee = time.time()
                    data_score = data.apply(lambda x: getScore_new(x[0], x[1], x[2], x[3]), axis=1)
                    data_score.to_csv(resultname, index=False, header=False)
                    print('1w数据计算得分消耗时间为：', time.time() - ee, 's')
                    flag = False
                else:
                    data = pd.DataFrame({'ul': [i for _ in range(10000)],
                                         'ur': [j for _ in range(10000)],
                                         'vl': [k for k in list(temp) for _ in range(100)],
                                         'vr': [k for _ in range(100) for k in list(temp)]})
                    # 写入case1的案例数据
                    # data.to_csv(filename, mode='a', index=False, header=False)
                    ee = time.time()
                    # temp_set.update(list(data.apply(lambda x: self.func(x[0], x[1], x[2], x[3]), axis=1)))
                    data_score = data.apply(lambda x: getScore_new(x[0], x[1], x[2], x[3]), axis=1)
                    data_score.to_csv(resultname, mode='a', index=False, header=False)
                    print('1w数据计算得分消耗时间为：', time.time() - ee, 's')
            co += 1
            print(resultname, '写入完毕', '消耗时间为：', time.time() - e, 's')
            filename = os.path.join(path, str(co) + '.csv')
            resultname = os.path.join(path2, str(co) + '.csv')
            flag = True
        print('存储时间为：', (time.time() - star) / 60, 'minutes')

    def case1_data(self):
        """
        function:L1=L2=L3=L4=0,x1≠x2,y1≠y2,写入1亿个数据
        :return:
        """

        star = time.time()

        path = r'data\case1'
        path2 = r'result\case1'
        co = 1
        filename = os.path.join(path, str(co) + '.csv')
        resultname = os.path.join(path2, str(co) + '.csv')
        self.makedir(path)
        self.makedir(path2)
        temp = np.arange(0, 1, 0.01)
        # 精度
        numb_round = int(log10(1 / self.deviation))
        count = 0
        flag = True
        e = time.time()
        from scoreFunction import getScore_new
        for i in temp:
            for j in temp:
                if flag:
                    data = pd.DataFrame({'ul': [i for _ in range(10000)],
                                         'ur': [j for _ in range(10000)],
                                         'vl': [k for k in list(temp) for _ in range(100)],
                                         'vr': [k for _ in range(100) for k in list(temp)]})
                    # 写入case1的案例数据
                    data = data[
                        (data['ul'] <= data['ur']) & (data['vl'] <= data['vr']) & (data['vl'] + data['vr'] <= 1)]
                    data.to_csv(filename, index=False, header=False)
                    count += data.__len__()
                    # temp_set.update(list(data.apply(lambda x:self.func(x[0],x[1],x[2],x[3]),axis=1)))
                    data_score = data.apply(lambda x: getScore_new(x[0], x[1], x[2], x[3]), axis=1)
                    data_score.to_csv(resultname, index=False, header=False)
                    flag = False
                else:
                    data = pd.DataFrame({'ul': [i for _ in range(10000)],
                                         'ur': [j for _ in range(10000)],
                                         'vl': [k for k in list(temp) for _ in range(100)],
                                         'vr': [k for _ in range(100) for k in list(temp)]})
                    # 写入case1的案例数据
                    data = data[
                        (data['ul'] <= data['ur']) & (data['vl'] <= data['vr']) & (data['vl'] + data['vr'] <= 1)]
                    data.to_csv(filename, mode='a', index=False, header=False)
                    count += data.__len__()
                    # temp_set.update(list(data.apply(lambda x: self.func(x[0], x[1], x[2], x[3]), axis=1)))
                    data_score = data.apply(lambda x: getScore_new(x[0], x[1], x[2], x[3]), axis=1)
                    data_score.to_csv(resultname, mode='a', index=False, header=False)
                if count >= 200000:
                    count = 0
                    co += 1
                    print(filename, '写入完毕', '消耗时间为：', time.time() - e, 's')
                    filename = os.path.join(path, str(co) + '.csv')
                    resultname = os.path.join(path2, str(co) + '.csv')
                    flag = True
        print('存储时间为：', (time.time() - star) / 60, 'minutes')

    def case2(self):
        """
        function:L1=L2=L3=L4=0,x1≠x2,y1≠y2
        :return:
        """
        flag = True

        star = time.time()

        path = r'data\case2'
        co = 1
        filename = os.path.join(path, str(co) + '.csv')
        self.makedir(path)

        temp = np.arange(0, 1, self.deviation * 5)
        # 精度
        numb_round = int(log10(1 / self.deviation))

        count = 0
        ivq_dict = {'ul': [], 'ur': [], 'vl': [], 'vr': []}
        for i in temp:
            for j in temp:
                ivq_dict['ul'].append(round(i, numb_round))
                ivq_dict['ur'].append(round(i, numb_round))
                ivq_dict['vl'].append(round(j, numb_round))
                ivq_dict['vr'].append(round(j, numb_round))
                # print(round(i, numb_round), round(i, numb_round))
                count += 1

            if len(ivq_dict['ur']) == 10000:
                # print(1111)
                if flag:
                    pd.DataFrame(ivq_dict).to_csv(filename, index=False, header=False)
                    flag = False
                else:
                    pd.DataFrame(ivq_dict).to_csv(filename, mode='a', index=False, header=False)
                ivq_dict = {'ul': [], 'ur': [], 'vl': [], 'vr': []}
            if count == 100000:
                # break
                co += 1
                count = 0
                print(filename, '写入完毕')
                filename = os.path.join(path, str(co) + '.csv')
                flag = True
        print(filename, '写入完毕')
        print('存储时间为：', (time.time() - star) / 60, 'minutes')


if __name__ == "__main__":
    GetTestData(0.0001).case1_data()

    pass
